import React, { useState, useEffect, useMemo } from 'react';
import { TableOperate } from '@/components/SelfIcon';
import { getButtons } from '@/utils/with-btns';
import { Popconfirm } from 'antd';
import { registerListTableEvent, registerListButtonEvent } from './utils';
import _ from 'lodash';
import { xhr_get, xhr_post_json } from '../_common/request';
import { FormattedMessage } from 'umi'
/**
 * 所有按钮初始化
 * @param hooks context
 * @param events  注册事件
 * @param params 执行事件参数
 * @returns  void
 */
export function useEventsRegister(hooks: any, events: any, params: any) {
  const { loading, searchButtons, buttons, tableButtons, validator } = params;
  useEffect(() => {
    if (!events) return
    if (events?.tableButtonsEvents) {
      registerListTableEvent(hooks?.current?.tableButtonsEvents, events?.tableButtonsEvents, params);
    }
    if (events?.buttonsEvents) {
      registerListButtonEvent(hooks?.current?.buttonsEvents, events?.buttonsEvents, params);
    }
  }, []);

  // 生成搜索按钮
  const getSearchButtons = () =>
    getButtons({ loading, buttons: searchButtons }, hooks.current.buttonsEvents);

  // 生成新增按钮
  const getTableTopButton = () =>
    getButtons({ loading, buttons: buttons }, hooks.current.buttonsEvents, validator);

  // 列表行项目操作按钮
  // @ts-ignore
  const operations = (id: string, row: any, extraPropsForOp: any, idx: number) => {
    const res: any = [];
    tableButtons?.map((o: any, index: any) => {
      if (validator?.checkColBtns && !validator.checkColBtns(o.key, row)) {
      } else {
        if (['shanchu', 'qiyong', 'jinyong', 'chongzhi', 'chehui'].includes(o.key)) {
          res.push(
            <Popconfirm
              title={<FormattedMessage id="buttons.yesOrNo" />}
              onConfirm={() => {
                hooks.current.tableButtonsEvents[o?.props?.hook](id, row, idx);
              }}
            >
              <TableOperate type={o.key} text={o.label} key={index} />
            </Popconfirm>
          );
        } else {
          res.push(
            <TableOperate
              key={o.key}
              type={`icon-${o.key}`}
              text={o.label}
              onClick={() => {
                hooks.current.tableButtonsEvents[o?.props?.hook](id, row, idx);
              }}
            />
          );
        }
      }


    });
    return res
  }

  return {
    getSearchButtons,
    getTableTopButton,
    operations
  }
}

export const useInitData=(a: Array<any> =[], api?: any, map?:any)=>{
  const [tableData, setDataSource] = useState<any>();
  useEffect(()=>{
   if(!api) return;
   if(api?.type?.toUpperCase() === 'POST')
   {
 const xhr = api?.type?.toUpperCase() === 'POST' ? xhr_post_json :xhr_get;
 xhr(api.url, api.params).then((res:any)=>{
    const d = res?.content
    if(map?.text){
      const nest = d[map?.text];
      setDataSource({
        dataSource: d,
      })
    }else {
      setDataSource({
        dataSource: d,
      })
    }
    }).catch((err:any)=>{
    console.error(`${err}`)
  })
   }
  },[api])
  useEffect(()=>{
    if(!Array.isArray(a)) return
      setDataSource({
        dataSource: a
      })
  }, [JSON.stringify(a)])
  return [tableData, setDataSource];
}
